package com.info3k.server.activate;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.info3k.server.PMF;
import com.info3k.server.domain.UserP;

public class ActivateUser extends HttpServlet {

	private PersistenceManager persistence;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>Activate account</TITLE></HEAD>");
		out.println("  <BODY>");

		String username = request.getParameter("username");
		String key = request.getParameter("registrationKey");
		
		if(username!=null && key!=null){
			Boolean act = activateUser(username, key);
			if(act==null) {
				out.println("Can't find user in database!");
			} else if(!act) {
				out.println("User already activate account! <a href=\"http://info-3k.appspot.com/\"/>Log in here</a>");
			} else {
				out.println("Account activated successfully! <a href=\"http://info-3k.appspot.com/\"/>Log in here</a>");
			}
		} else {
			out.println("Invalid username or registration key!");
		}
		
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
	
	public Boolean activateUser(String username, String key) {
		persistence = PMF.get().getPersistenceManager();
		Key k = KeyFactory.createKey(UserP.class.getSimpleName(), Long.valueOf(key));
		UserP userP = getUserByKey(k);
		if(userP!=null){
			if(userP.getActivated()!=null && userP.getActivated()) return false;
			userP.setActivated(true);
			persistence.makePersistent(userP);
			persistence.close();
			return true;
		}
		return null;
	}
	
	private UserP getUserByKey(Key key){
    	Query q = persistence.newQuery("select from " + UserP.class.getName() + " where id == :keys");
    	
    	List<UserP> usersP = (List<UserP>)q.execute(key);
    	
    	if(usersP.size()>0) return usersP.get(0); 
    	return null;
	}

}
